package org.jsola.hr.web;

import org.jsola.core.Result;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.service.ITransferAccountsBatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;


/**
 * @author zhr
 */
@RestController("hrAliPayController")
@RequestMapping(HrConstants.API_PATH + "/v1/aliPay")
public class AliPayController implements IAliPayControllerAPI {

    @Autowired
    ITransferAccountsBatchService transferAccountsBatchService;


    @Override
    @GetMapping("back")
    public Result<String> backUserInfo(String state) {
        return Result.success(state);
    }

    @Override
    @PostMapping("/offerAliPay")
    public String offerAliPay(HttpServletRequest request) {
        String requestBodyStr = readAsChars2(request);
        return transferAccountsBatchService.offerAliPay(requestBodyStr);
    }

    @Override
    @PostMapping("/offerAliSafetyPay")
    public String offerAliSafetyPay(HttpServletRequest request) {
        String requestBodyStr = readAsChars2(request);
        return transferAccountsBatchService.offerAliSafetyPay(requestBodyStr);
    }

    public static String readAsChars2(HttpServletRequest request) {
        InputStream is = null;
        try {
            is = request.getInputStream();
            StringBuilder sb = new StringBuilder();
            byte[] b = new byte[4096];
            for (int n; (n = is.read(b)) != -1; ) {
                sb.append(new String(b, 0, n));
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}

